(function (G) {
  window["components_TopicDialog_TopicDialog"]({
    "component": true,
    "usingComponents": {
      "drawer": "/components/Drawer/Drawer"
    }
  }, {
    template: '#TEMPLATE_components_TopicDialog_TopicDialog',
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      title: {
        type: String,
        default: '知识点出题'
      },
      courseId: {  // 接收父组件传递的 courseId
        type: String,
        required: true
      },
      chapter: {  // 接收父组件传递的 checkedNodesdata
        type: Object,
        required: true
      },
      halfCheckedNodesdata: {
        type: Array,
        required: true
      }
    },
    data: function () {
      return {
        loading: false,
        questions: [],
        answerTag: [],
        knowledgePoints: "", // 用户输入内容绑定
        selectedType: null,
        selectedType: 1,     // 默认为单选题
        questionCount: 1,
        // selectedDifficulty: "简单",
        selectedDifficulty: 1,  // 默认为简单
        selectedScenario: 1,    // 默认为结合场景
        // selectedScenario: "结合场景",
        editDialogVisible: false,
        isEditMode: false,
        editForm: {
          id: '',
          question: '',
          type: null,
          optionsLev: [],
          answer: '',
          analysis: '',
          lev: '',
          optionCount: 0
        },
        formRules: {
          question: [
            { required: true, message: '题干不能为空', trigger: 'blur' },
            { max: 1000, message: '题干不能超过 1000 个字符', trigger: 'blur' }
          ],
          type: [
            { required: true, message: '请选择题目类型', trigger: 'change' }
          ],
          answer: [
            { required: true, message: '答案不能为空', trigger: 'blur' },
            { max: 1000, message: '答案不能超过 1000 个字符', trigger: 'blur' }
          ],
          lev: [
            { required: true, message: '难度等级不能为空', trigger: 'change' }
          ]
        },
        questionTypes: [
          { label: '单选题', value: 1 },
          { label: '判断题', value: 2 },
          { label: '多选题', value: 3 },
          { label: '填空题', value: 4 },
          { label: '简答题', value: 5 },
        ],
        difficultyLevels: [
          { label: '简单', value: 1 },
          { label: '中等', value: 2 },
          { label: '困难', value: 3 }
        ],
        difficultyScenario: [
          { label: '结合场景', value: 1 },
          { label: '普通题目', value: 0 },
        ],
        promptText: '', // 存储提示语文本
      }
    },
    computed: {
      placeholderContent: {
        get() {
          return this.promptText;
        },
        set(newValue) {
          this.promptText = newValue;
          this.parseAndUpdateSettings(newValue);
        }
      },

      canGenerate() {
        return this.selectedType && this.questionCount > 0;
      },
    },
    methods: {
      handleClose() {
        this.setData({
          selectedType: 1,
          questionCount: 1,
          selectedDifficulty: 1,
          selectedScenario: 1,
          knowledgePoints: "",
          questions: []
        });
        this.triggerEvent('close');
      },
      // 编辑题目
      // 修改编辑题目方法，添加当前编辑题目的索引
      editQuestion(question, index) {
        this.isEditMode = true;
        this.currentEditIndex = index; // 添加当前编辑题目的索引
        this.editForm = {
          id: question.id,
          question: question.description,
          type: this.getQuestionTypeValue(question.type),
          optionsLev: this.parseOptions(question.options),
          answer: question.answer,
          analysis: question.analysis,
          lev: question.difficulty,
          optionCount: question.options ? question.options.length : 0,
          scoring: this.getScoring(question.type)  // 根据题目类型获取评分规则
        };
        this.editDialogVisible = true;
      },
      cancelEdit() {
        this.editDialogVisible = false;
        this.editForm = this.getEmptyEditForm();
        this.isEditMode = false;
      },
      // 保存编辑
      // 修改保存编辑方法，更新前端显示
      async saveEdit() {
        try {
          await this.$refs.editForm.validate();
          const updatedQuestion = {
            description: this.editForm.question,
            type: this.getQuestionType(this.editForm.type),
            difficulty: this.editForm.lev,
            knowledge: this.getData('knowledgePoints'),
            options: this.processEditedOptions(this.editForm),
            answer: this.editForm.answer,
            analysis: this.editForm.analysis,
            scoring: this.getScoring(this.getQuestionType(this.editForm.type))  // 根据题目类型获取评分规则
          };

          // 更新前端显示的题目
          const questions = this.getData('questions');
          questions[this.currentEditIndex] = updatedQuestion;
          this.setData({ questions: questions });

          this.$message({
            message: '修改成功',
            type: 'success'
          });

          this.editDialogVisible = false;
        } catch (error) {
          console.error('修改失败:', error);
          this.$message({
            message: '修改失败，请检查表单',
            type: 'error'
          });
        }
      },
      // 处理编辑后的选项
      processEditedOptions(editForm) {
        if (!editForm.optionsLev || editForm.optionsLev.length === 0) {
          return [];
        }

        // 处理选择题选项
        if (editForm.type === 1 || editForm.type === 3) {
          return editForm.optionsLev.map((text, index) => {
            const letter = String.fromCharCode(65 + index);
            const isCorrect = editForm.type === 1
              ? editForm.answer === letter
              : editForm.answer.split(';').includes(letter);

            return {
              text: text,
              isCorrect: isCorrect,
              letter: letter
            };
          });
        }

        return [];
      },
      // 处理选项数量变化
      handleOptionCountChange(value) {
        const currentLength = this.editForm.optionsLev.length;
        if (currentLength < value) {
          for (let i = currentLength; i < value; i++) {
            this.editForm.optionsLev.push('');
          }
        } else if (currentLength > value) {
          this.editForm.optionsLev = this.editForm.optionsLev.slice(0, value);
        }
      },
      // 获取空的编辑表单
      getEmptyEditForm() {
        return {
          id: '',
          question: '',
          type: null,
          optionsLev: [],
          answer: '',
          analysis: '',
          lev: '',
          optionCount: 0
        };
      },
      // 解析选项数据
      parseOptions(options) {
        if (!options) return [];
        return options.map(opt => opt.text);
      },
      // 格式化答案显示
      formatAnswerDisplay(answer) {
        // 如果答案是单个字母或简单字符串，直接返回
        if (typeof answer === 'string' && answer.length <= 5) {
          return answer;
        }

        // 如果答案是字符串格式的数组或对象，尝试解析
        if (typeof answer === 'string') {
          try {
            const parsedAnswer = JSON.parse(answer);
            return this.formatAnswerDisplay(parsedAnswer);
          } catch (e) {
            // 如果解析失败，直接返回原始答案
            return answer;
          }
        }

        // 如果答案是数组，直接格式化为 "A、B" 的形式
        if (Array.isArray(answer)) {
          return answer.join('、');
        }

        // 如果答案是对象，根据需要格式化显示
        if (typeof answer === 'object' && answer !== null) {
          try {
            const formattedFunctions = (answer.functions || [])
              .map(func => `${func.name}: ${func.description} (${func.parameters.join(', ')})`)
              .join('；');

            return `分数: ${answer.score || 0}；功能描述: ${formattedFunctions}`;
          } catch (e) {
            return String(answer);
          }
        }

        // 其他情况，直接返回原答案
        return answer || '';
      },


      getTagType(difficultyTag) {
        switch (difficultyTag.toString()) { // 确保字符串比较
          case "1":
            return "success"; // 绿色
          case "2":
            return "warning"; // 黄色
          case "3":
            return "danger"; // 红色
          default:
            return "info"; // 默认蓝色
        }
      },
      getScoring(type) {
        const scoringRules = {
          "1": "答对得2分，答错不得分",
          "3": "答对得5分，答错或答少不得分",
          "2": "答对得2分，答错不得分",
          "4": "答对一个空3分，答错不得分",
          "5": "1. 答对一个点得2分\n2. 答错不得分",
        };
        return scoringRules[type] || "答对得5分，答错不得分";  // 修改默认返回值
      },
      async generateQuestions() {
        console.log('传来的id',this.courseId);
        console.log('传来的id',this.chapter);
        console.log('传来的halfCheckedNodesdata',this.halfCheckedNodesdata);
        const labels = this.halfCheckedNodesdata.map(node => node.label);

        console.log(labels); // 输出: ["定位系统与地图学", "地图与地图学的基本知识"]
        
        this.setData({ loading: true, questions: [] });

        try {
          const response = await G.get('{JAVAURL}/spark/createTopic', {
            // knowledgePoints: this.getData('knowledgePoints'),
            type: this.getData('selectedType'),
            topicNum: this.getData('questionCount'),
            SpCourseId: 1,
            SpChapterId: 1,
            Level: this.getData('selectedDifficulty'),
            Scenario: this.getData('selectedScenario'),
            knowledgePoints: this.chapter.label,
            TreeNode: labels
          });

          console.log('API Response:', response);

          const processedQuestions = response.data.map(item => ({
            type: this.getQuestionType(item.type),
            difficulty: this.getQuestionLevel(item.lev),
            knowledge: this.getData('knowledgePoints'),
            description: item.question,
            options: this.processOptions(item),
            answer: item.answer,
            analysis: item.analysis,
            scoring: this.getScoring(item.type),
            answerComment: item.answerComment
          }));

          console.log('Processed Questions:', processedQuestions);

          this.setData({ questions: processedQuestions });
        } catch (error) {
          console.error('获取题目失败', error);
          this.$message({
            message: '获取题目失败，请重试',
            type: 'error'
          });
        } finally {
          this.setData({ loading: false });
        }
      },

      getQuestionType(type) {
        const types = {
          1: "单选题",
          2: "判断题",
          3: "多选题",
          4: "填空题",
          5: "简答题"
        };
        return types[type] || "未知";
      },

      getQuestionLevel(lev) {
        const levels = {
          "1": "简单",
          "2": "中等",
          "3": "困难"
        };
        return levels[lev] || "未知";
      },

      processOptions(item) {
        // 如果没有选项数据，返回空数组
        if (!item.optionArr && !item.optionsLev) return [];
        console.log('item',item.type);
        
        // 根据题目类型处理选项
        switch (item.type) {
          case 1: // 单选题
            return processSingleChoiceOptions(item);
          case 2: // 判断题
            return processJudgementOptions(item);
          case 3: // 多选题
            return processMultiChoiceOptions(item);
          default:
            return [];
        }

        // 处理单选题选项
        function processSingleChoiceOptions(item) {
          let options = parseOptions(item);
          let correctAnswer = parseAnswer(item.answer);

          return options.map((opt, index) => {
            const letter = String.fromCharCode(65 + index);
            return {
              text: opt.replace(/^[A-E]\.\s*/, '').trim(),
              isCorrect: correctAnswer.includes(letter),
              letter: letter
            };
          });
        }

        // 处理判断题选项
        function processJudgementOptions(item) {
          // 判断题固定返回两个选项
          return [
            {
              text: '正确',
              isCorrect: item.answer === '正确',
          
            },
            {
              text: '错误',
              isCorrect: item.answer === '错误',
              
            }
          ];
        }

        // 处理多选题选项
        function processMultiChoiceOptions(item) {
          let options = parseOptions(item);
          let correctAnswers = parseAnswer(item.answer);

          return options.map((opt, index) => {
            const letter = String.fromCharCode(65 + index);
            return {
              text: opt.replace(/^[A-E]\.\s*/, '').trim(),
              isCorrect: correctAnswers.includes(letter),
              letter: letter
            };
          });
        }

        // 通用的选项解析函数
        function parseOptions(item) {
          let options = [];
          if (item.optionsLev) {
            try {
              options = JSON.parse(item.optionsLev);
            } catch (e) {
              options = item.optionsLev.split(';').map(opt => opt.trim());
            }
          } else if (item.optionArr) {
            options = item.optionArr;
          }
          return options;
        }

        // 通用的答案解析函数
        function parseAnswer(answer) {
          if (!answer) return [];
          try {
            return JSON.parse(answer);
          } catch (e) {
            return answer.split(';').map(a => a.trim());
          }
        }
      },



      saveDraft() {
        this.triggerEvent('saveDraft', this.getData('questions'));
      },

      async confirmPublish() {
        console.log('confirmPublish triggered');
        console.log('questions:', this.getData('questions'));

        if (!this.getData('questions') || this.getData('questions').length === 0) {
          this.$message({
            message: '请先生成题目',
            type: 'warning'
          });
          return;
        }

        try {
          const questions = this.getData('questions');
          console.log('this.chapter.id:', this.chapter.id);
          console.log('this.courseId:', this.courseId);
          // const courseIdLong = parseInt(this.courseId); 
          // console.log('courseIdLong:', courseIdLong);
          console.log('questions:', questions); 
          
          const promises = questions.map(question => {
            // 构造符合后端接口的数据格式
            const topicData = {
              question: question.description,
              type: this.getQuestionTypeValue(question.type),
              lev: this.getQuestionLevelValue(question.difficulty),
              analysis: question.analysis,
              optionsLev: this.formatOptionsForBackend(question.options),
              answer: this.formatAnswerForBackend(question),
              answerComment: question.answerComment,
              spChapterId: this.chapter.id,
              // spCourseId: courseIdLong,
              spCourseId:this.courseId

            };

            // 用后端接口
            return G.post('{JAVAURL}/sp-topic/add', topicData);
          });

          await Promise.all(promises);
          this.$message({
            message: '发布成功',
            type: 'success'
          });
          this.handleClose();
          // 触发父组件刷新列表
          this.triggerEvent('publishSuccess');
        } catch (error) {
          console.error('发布失败:', error);
          this.$message({
            message: '发布失败，请重试',
            type: 'error'
          });
        }
      },

      // 将题目类型文字转换为对应的数值
      getQuestionTypeValue(typeText) {
        const typeMap = {
          "单选题": 1,
          "判断题": 2,
          "多选题": 3,
          "填空题": 4,
          "简答题": 5
        };
        return typeMap[typeText] || 1;
      },

      // 将难度文字转换为对应的数值
      getQuestionLevelValue(levelText) {
        const levelMap = {
          "简单": 1,
          "中等": 2,
          "困难": 3
        };
        return levelMap[levelText] || 1;
      },

      // 格式化选项数据
      formatOptionsForBackend(options) {
        if (!options || options.length === 0) return '';

        // 将选项数组转换为分号分隔的字符串
        return options.map(opt => opt.text).join(';');
      },

      // 格式化答案数据
      formatAnswerForBackend(question) {
        if (!question.options || question.options.length === 0) {
          return question.answer;
        }

        // 对于选择题，找出正确选项的字母
        const correctOptions = question.options
          .filter(opt => opt.isCorrect)
          .map(opt => opt.letter)
          .join(';');

        return correctOptions || question.answer;
      },

      // 生成默认提示语
      generateDefaultPrompt() {
        console.log('Generating prompt with chapter:', this.chapter);
        const scenarioText = this.selectedScenario === 1
          ? "3.需要结合场景案例(应用题) 生成题目"
          : "3.不结合场景案例，普通题目";

        const selectedTypeLabel = this.questionTypes.find((type) => type.value === this.selectedType)?.label || '未选择';
        const selectedDifficultyLabel = this.difficultyLevels.find((level) => level.value === this.selectedDifficulty)?.label || '未选择';
        const chapterLabel = this.chapter?.label || '请选择章节';

        return `1.根据所选知识点大纲，随机生成，给出答案解析。\n` +
          `2.题目数量${this.questionCount}道，类型是${selectedTypeLabel}，难度是${selectedDifficultyLabel}。\n` +
          `${scenarioText}\n` +
          `4.题目大纲包括: ${chapterLabel}\n` 
          // `5.请输入知识点: ${this.knowledgePoints}`;
      },

      // 解析文本并更新设置
      parseAndUpdateSettings(text) {
        // 解析题目数量
        const countMatch = text.match(/题目数量(\d+)道/);
        if (countMatch && countMatch[1]) {
          this.questionCount = parseInt(countMatch[1]);
        }

        // 解析题目类型
        const typeMatch = text.match(/类型是(.*?)，/);
        if (typeMatch && typeMatch[1]) {
          const matchedType = this.questionTypes.find(type => type.label === typeMatch[1]);
          if (matchedType) {
            this.selectedType = matchedType.value;
          }
        }

        // 解析难度
        const difficultyMatch = text.match(/难度是(.*?)。/);
        if (difficultyMatch && difficultyMatch[1]) {
          const matchedDifficulty = this.difficultyLevels.find(level => level.label === difficultyMatch[1]);
          if (matchedDifficulty) {
            this.selectedDifficulty = matchedDifficulty.value;
          }
        }

        // 解析场景设置
        if (text.includes("需要结合场景案例")) {
          this.selectedScenario = 1;
        } else if (text.includes("不结合场景案例")) {
          this.selectedScenario = 0;
        }

        // 修改知识点解析逻辑
        const knowledgeMatch = text.match(/5\.请输入知识点:\s*(.*?)$/m);
        if (knowledgeMatch && knowledgeMatch[1]) {
          // 只取冒号后面的内容作为知识点
          this.knowledgePoints = knowledgeMatch[1].trim();
        }
      },

      // 处理文本变化
      handleTextChange(newValue) {
        this.promptText = newValue;
        this.parseAndUpdateSettings(newValue);
      },

      // 处理设置变化
      handleSettingChange() {
        // 直接更新提示文本
        this.$nextTick(() => {
          this.promptText = this.generateDefaultPrompt();
        });
      },

      // 添加所有的处理方法到 methods 中
      handleTypeClick(value) {
        this.selectedType = value;
        this.handleSettingChange();
      },

      handleDifficultyClick(value) {
        this.selectedDifficulty = value;
        this.handleSettingChange();
      },

      handleScenarioClick(value) {
        this.selectedScenario = value;
        this.handleSettingChange();
      },

      handleCountChange(value) {
        this.questionCount = value;
        this.handleSettingChange();
      },

      handleDialogOpen() {
        // 对话框打开时的处理逻辑
        this.$nextTick(() => {
          // 重置表单数据
          this.setData({
            selectedType: 1,
            questionCount: 1,
            selectedDifficulty: 1,
            selectedScenario: 1,
            knowledgePoints: "",
            questions: []
          });
          
          // 更新提示语
          this.promptText = this.generateDefaultPrompt();
        });
      },
    },
    created() {
      // 初始化提示语
      this.promptText = this.generateDefaultPrompt();
    },
    watch: {
      selectedType: {
        handler() {
          this.handleSettingChange();
        },
        immediate: true
      },
      questionCount: {
        handler() {
          this.handleSettingChange();
        },
        immediate: true
      },
      selectedDifficulty: {
        handler() {
          this.handleSettingChange();
        },
        immediate: true
      },
      selectedScenario: {
        handler() {
          this.handleSettingChange();
        },
        immediate: true
      },
      knowledgePoints: {
        handler() {
          this.handleSettingChange();
        },
        immediate: true
      },
      chapter: {
        handler(newVal) {
          console.log('TopicDialog received new chapter:', newVal);
          if (newVal && newVal.label) {
            // 当接收到新的 chapter 数据时，更新提示语
            this.$nextTick(() => {
              this.promptText = this.generateDefaultPrompt();
            });
          }
        },
        immediate: true,
        deep: true
      }
    }
  })
})(Y) 